package com.njupt.backtracking;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;

/**
 * @Author: wujiaming
 * @CreateTime: 2024/12/13 9:44
 * @Description: 40. 组合总和 II
 * @Version: 1.0
 */


public class CombinationSum2 {

    public List<List<Integer>> combinationSum2(int[] candidates, int target) {

        List<List<Integer>> results = new ArrayList<>();
        List<Integer> result = new LinkedList<>();
        int startIndex = 0;
        int sum = 0;
        Arrays.sort(candidates);
        boolean[] used = new boolean[candidates.length];
        traceBacking(startIndex,sum,candidates,target,results,result,used);
//        traceBacking1(startIndex,sum,candidates,target,results,result);
        return results;
    }

    private void traceBacking(int startIndex, int sum, int[] candidates, int target, List<List<Integer>> results, List<Integer> result,boolean[] used) {

        if(sum == target){
            results.add(new ArrayList(result));
            return;
        } else if (sum>target) {
            return;
        }

        for (int i = startIndex; i < candidates.length ; i++) {

            if(i>startIndex && candidates[i] == candidates[i-1] && used[i-1] == false){
                continue;
            }
            sum += candidates[i];
            result.add(candidates[i]);
            used[i] = true;
            traceBacking(i+1,sum,candidates,target,results,result,used);
            sum -= candidates[i];
            result.remove(result.size()-1);
            used[i] = false;
        }
    }

    private void traceBacking1(int startIndex, int sum, int[] candidates, int target, List<List<Integer>> results, List<Integer> result){
        if(sum == target){
            results.add(new ArrayList<>(result));
            return;
        } else if (sum>target) {
            return;
        }
        for (int i = startIndex; i <candidates.length ; i++) {

            if(i>startIndex && candidates[i] == candidates[i-1]){
                continue;
            }
            sum += candidates[i];
            result.add(candidates[i]);
            traceBacking1(i+1,sum,candidates,target,results,result);
            sum -= candidates[i];
            result.remove(result.size()-1);

        }
    }

    public static void main(String[] args) {
        int[] candidates = {2,5,2,1,2};
        CombinationSum2 test = new CombinationSum2();
        List<List<Integer>> lists = test.combinationSum2(candidates, 5);
        System.out.println(lists);
    }
}
